<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('search.saleOrder')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :placeholder="$t('placeholder.pleaseInputSaleOrder')" v-model="queryParam.number"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('search.salesMan')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :placeholder="$t('placeholder.pleaseSelectSalesMan')" showSearch optionFilterProp="children"
                            allowClear="true"
                            v-model="queryParam.salesMan">
                    <a-select-option v-for="(item, index) in personList.options" :key="item.value || item.id || index"
                                     :value="item.value || item.id">
                      {{ item.text || item.label || item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('search.orderDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                    style="width: 100%"
                    v-model="queryParam.createTimeRange"
                    format="YYYY-MM-DD"
                    :placeholder="[$t('placeholder.pleaseInputStartTime'), $t('placeholder.pleaseInputEndTime')]"
                    @change="onDateChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('search.customer')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :placeholder="$t('placeholder.pleaseSelectCustomer')" showSearch optionFilterProp="children"
                            v-model="queryParam.supplier">
                    <a-select-option v-for="(item, index) in personList.options" :key="item.value || item.id || index"
                                     :value="item.value || item.id">
                      {{ item.text || item.label || item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!--              <a-col :md="6" :sm="24">-->
              <!--                <a-form-item :label="$t('search.chequeStatus')" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
              <!--                  <a-select v-model="queryParam.chequeStatus" placeholder="请选择支票状态">-->
              <!--                    <a-select-option value="-1">未收支票</a-select-option>-->
              <!--                    <a-select-option value="0">未兑现</a-select-option>-->
              <!--                    <a-select-option value="1">{{$t('status.realized')}}</a-select-option>-->
              <!--                    <a-select-option value="2">退票</a-select-option>-->
              <!--                  </a-select>-->
              <!--                </a-form-item>-->
              <!--              </a-col>-->
              <!--              <a-col :md="6" :sm="24">-->
              <!--                <a-form-item label="支付类型" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
              <!--                  <a-select v-model="queryParam.payType" placeholder="请选择支付类型">-->
              <!--                    <a-select-option value="0">未知</a-select-option>-->
              <!--                    <a-select-option value="1">现金</a-select-option>-->
              <!--                    <a-select-option value="2">支票</a-select-option>-->
              <!--                  </a-select>-->
              <!--                </a-form-item>-->
              <!--              </a-col>-->
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator" style="margin-top: 5px">
          <a-button type="primary" icon="search" @click="searchQuery">{{ $t('button.search') }}</a-button>
          <a-button style="margin-left: 8px" icon="reload" @click="searchReset">{{ $t('button.reset') }}</a-button>
          <a-button style="margin-left: 8px" v-print="'#reportPrint'" icon="printer">{{ $t('button.print') }}</a-button>
          <a-button style="margin-left: 8px" @click="exportExcel" icon="download">{{ $t('button.export') }}</a-button>
        </div>
        <!-- table区域-begin -->
        <section ref="print" id="reportPrint">
          <a-table
            bordered
            ref="table"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :components="handleDrag(columns)"
            :pagination="ipagination"
            :scroll="scroll"
            :loading="loading"
            @change="handleTableChange">
            <template slot="footer">
              <tr>
                <th colspan="7"></th>
                <th>{{ $t('title.uncashedChequeAmount') }}{{ summaryData.uncashedChequeAmount }}</th>
                <th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                    $t('title.bouncedChequeAmount')
                  }}{{ summaryData.bouncedChequeAmount }}
                </th>
                <th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                    $t('title.totalCollectAmount')
                  }}{{ summaryData.totalCollectAmount }}
                </th>
                <th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                    $t('title.customCollectAmount')
                  }}{{ summaryData.customCollectAmount }}
                </th>
                <th colspan="5"></th>
              </tr>
            </template>
          </a-table>
        </section>
        <!-- table区域-end -->
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {getAction} from '@/api/manage'
import moment from 'moment/moment'
import dayjs from 'dayjs'
import {getFormatDate, getPrevMonthFormatDate} from '@/utils/util'
import {findBySelectCus} from '@api/api'
import {getPersonByNumType} from '../../api/api'

export default {
  name: 'SaleSumReport',
  mixins: [JeecgListMixin],
  data () {
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 18, offset: 1 },
      description: '销售收入汇总',
      personList: {
        options: [],
        value: ''
      },
      cusList: [],
      // 查询条件
      queryParam: {
        number: '',
        salesMan: '',
        beginTime: getPrevMonthFormatDate(3),
        endTime: getFormatDate(),
        createTimeRange: [moment(getPrevMonthFormatDate(3)), moment(getFormatDate())],
        supplier: '',
        chequeStatus: '',
        payType: ''
      },
      // 表头
      columns: [
        {
          title: '#', dataIndex: 'rowIndex', width: 50, align: 'center',
          customRender: (t, r, index) => (t !== this.$t('message.total1')) ? (parseInt(index) + 1) : t
        },
        // { title: this.$t('search.saleOrder'), dataIndex: 'number', width: 140 },
        {title: this.$t('search.salesMan'), dataIndex: 'salesMan', width: 90},
        {title: this.$t('search.orderDate'), dataIndex: 'createTime', width: 100},
        {title: this.$t('search.accountName'), dataIndex: 'accountName', width: 100},
        {title: this.$t('search.customer'), dataIndex: 'supplier', width: 100},
        {title: this.$t('search.outTime'), dataIndex: 'oTime', width: 100},
        {title: this.$t('search.signTime'), dataIndex: 'sTime', width: 100},
        {
          title: this.$t('search.overdueDay'),
          dataIndex: 'overdueDay',
          width: 100,
          customRender: (text) => {
            if (text > 0) {
              return <span style="color: red;">{text}</span>
            }
            return text
          }
        },
        {title: this.$t('search.outBillNo'), dataIndex: 'oNumber', width: 110},
        {title: this.$t('search.outTotalPrice'), dataIndex: 'oPrice', width: 100},
        { title: this.$t('search.chequeAmount'), dataIndex: 'chequeAmount', width: 100 },
        {title: this.$t('search.chequeNumber'), dataIndex: 'chequeNumber', width: 110},
        {title: this.$t('search.chequePayDate'), dataIndex: 'payDate', width: 90},
        {title: this.$t('search.collectBillNumber'), dataIndex: 'collectBillNumber', width: 100},
        { title: this.$t('search.collectRealAmount'), dataIndex: 'collectRealAmount', width: 100 },
        {
          title: this.$t('search.rStatus'),
          dataIndex: 'rStatus',
          width: 80,
          customRender: (text) => text === 1 ? this.$t('status.return') : this.$t('status.noReturn')
        },
        {title: this.$t('search.rNumber'), dataIndex: 'rNumber', width: 110},
        {title: this.$t('search.rPrice'), dataIndex: 'rPrice', width: 100},
        {
          title: this.$t('search.chequeStatus'),
          dataIndex: 'chequeStatus',
          width: 100,
          customRender: (text) => {
            const statusMap = {
              '-1': this.$t('status.unReceivedCheque'),
              0: this.$t('status.unRealized'),
              1: this.$t('status.realized'),
              2: this.$t('status.returnedCheque'),
              3: this.$t('status.returnToCustomer')
            }
            return statusMap[text] || text
          }
        },
        {
          title: this.$t('search.payType1'),
          dataIndex: 'payType',
          width: 100,
          customRender: (text) => {
            const payTypeMap = {
              '0': this.$t('status.unknown'),
              '1': this.$t('status.cash'),
              '2': this.$t('status.cheque')
            }
            return payTypeMap[text] || text
          }
        }
      ],
      url: {
        list: '/depotHead/saleSumReport'
      },
      summaryData: {
        uncashedChequeAmount: 0,
        bouncedChequeAmount: 0,
        totalCollectAmount: 0,
        customCollectAmount: 0
      }
    }
  },
  created () {
    this.ipagination.pageSize = 100
    this.initUser()
    this.initCustomer()
    this.loadData(1)
  },
  methods: {
    initUser () {
      let that = this
      getPersonByNumType({type: 1}).then((res) => {
        if (res) {
          that.personList.options = res
        }
      })
    },
    initCustomer () {
      let that = this
      findBySelectCus({}).then((res) => {
        if (res) {
          that.cusList = res
        }
      })
    },
    onDateChange (value, dateString) {
      this.queryParam.beginTime = dayjs(dateString[0]).format('YYYY-MM-DD')
      this.queryParam.endTime = dayjs(dateString[1]).format('YYYY-MM-DD')
      if (dateString[0] && dateString[1]) {
        this.queryParam.createTimeRange = [moment(dateString[0]), moment(dateString[1])]
      }
    },
    searchQuery () {
      this.loadData(1)
    },
    getQueryParams () {
      let param = Object.assign({}, this.queryParam)
      if (this.queryParam.createTimeRange && this.queryParam.createTimeRange.length === 2) {
        param.beginTime = dayjs(this.queryParam.createTimeRange[0]).format('YYYY-MM-DD')
        param.endTime = dayjs(this.queryParam.createTimeRange[1]).format('YYYY-MM-DD')
      }
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return param
    },
    loadData (arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.code === 200) {
          this.dataSource = res.data.rows
          this.ipagination.total = res.data.total

          this.calculateSummary()
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        this.$message.error(this.$t('message.loadDataFailed'))
      }).finally(() => {
        this.loading = false
      })
    },
    searchReset () {
      this.queryParam = {
        number: '',
        salesMan: '',
        createTimeRange: [],
        supplier: '',
        chequeStatus: '',
        payType: ''
      }
      this.loadData(1)
    },
    calculateSummary () {

      let uncashedChequeAmount = 0
      let bouncedChequeAmount = 0
      let totalCollectAmount = 0
      let customCollectAmount = 0

      if (Array.isArray(this.dataSource)) {
        this.dataSource.forEach(item => {

          if (item.chequeStatus === 0) {
            uncashedChequeAmount += parseFloat(item.chequeAmount || 0)
          }
          if (item.chequeStatus === 2) {
            bouncedChequeAmount += parseFloat(item.chequeAmount || 0)
          }
          totalCollectAmount += parseFloat(item.collectRealAmount || 0)

          if (item.chequeStatus === 1) {
            //已兑现
            customCollectAmount += parseFloat(item.chequeAmount || 0)
          }
          if (item.rStatus === 1) {
            //退货
            customCollectAmount -= parseFloat(item.collectRealAmount || 0)
          }

        })
      }

      this.summaryData = {
        uncashedChequeAmount: uncashedChequeAmount.toFixed(2),
        bouncedChequeAmount: bouncedChequeAmount.toFixed(2),
        totalCollectAmount: totalCollectAmount.toFixed(2),
        customCollectAmount: customCollectAmount.toFixed(2)
      }
    },
    exportExcel () {
      let list = []
      let head = '销售员,订单日期,收款账户,客户,出库时间,签收时间,逾期天数,出库单号,出库单金额,支票金额,支票号,兑现日期,收款单单号,收款单金额,退货状态,退货单号,退货金额,支票状态,支付方式'
      for (let i = 0; i < this.dataSource.length; i++) {
        let item = []
        let ds = this.dataSource[i]
        item.push(ds.salesMan, ds.createTime, ds.accountName, ds.supplier, ds.oTime, ds.sTime, ds.overdueDay, ds.oNumber, ds.oPrice,
          ds.chequeAmount, ds.chequeNumber, ds.payDate, ds.collectBillNumber, ds.collectRealAmount, ds.rStatus === 1 ? '已退货' : '未退货', ds.rNumber, ds.rPrice,
          ['未收支票', '未兑现', '已兑现', '退票', '退还客户'][ds.chequeStatus + 1],
          ds.payType === 1 ? '现金' : '支票')
        list.push(item)
      }
      let tip = '订单日期：' + this.queryParam.beginTime + '~' + this.queryParam.endTime
      this.handleExportXlsPost('销售收入汇总', '销售收入汇总', head, tip, list)
    }
  }
}
</script>

<style scoped>
@import '~@assets/less/common.less';

.overdue-red {
  color: red;
}
</style>